<template>
	<qh-page-view title="商品">
		<view class="box">
			<view class="list" v-for="(item, index) in goodsList" :key="index" :for-id="index">
				<view class="m-list">
					<view class="list-left" @tap="toDetail" :data-id="item.goods_id">
						<image :src="item.goods_image" mode="widthFix"></image>
					</view>
					<view class="list-right">
						<view class="name" @tap="toDetail" :data-id="item.goods_id">
							{{item.goods_name?item.goods_name:'商品名称'}}
						</view>
						<view class="bottom">
							<view class="right-list">
								<view class="goods_sku" v-if="item.attribute_state==2" @tap.stop="chooseSku" :data-index="index">
									<text>{{item.sku_name?item.sku_name:'选规格'}}</text>
									<image src="/static/images/arrow-right.png"></image>
								</view>
								<view v-else></view>
								<view class="day">
									<text>{{item.time}}</text>
									<text>天 PLUS会员</text>
								</view>
							</view>
							<view class="right-list">
								<view class="price-color">￥{{item.online_price?item.online_price:'商品价格'}}</view>
								<view class="buy" @tap="toBuyGoods" :data-index="index">立即购买</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="list" v-for="(item, index) in groupList" :key="index" :for-id="index">
				<view class="m-list" @tap="seeMeal" :data-index="index">
					<view class="list-left">
						<image :src="item.image" mode="widthFix"></image>
					</view>
					<view class="list-right">
						<view class="name">{{item.meal_name?item.meal_name:'套餐名称'}}</view>
						<view class="bottom">
							<view class="right-list">
								<view></view>
								<view class="day">
									<text>{{item.time}}</text>
									<text>天 PLUS会员</text>
								</view>
							</view>
							<view class="right-list">
								<view class="goods-num">共{{item.goodsList.length}}件商品</view>
								<view class="buy">查看商品</view>
							</view>
						</view>
					</view>

				</view>
			</view>
			<view class="meal-container" v-if="showMealDetail">
				<view class="meal-content">
					<view class="meal-title-box">
						<view class="meal-title">{{mealDetail.meal_name}}</view>
						<view class="meal-time">{{mealDetail.time}}天 PLUS会员</view>
					</view>
					<view @click.stop="closeMealDetail">
						<icon class="meal-close" type="cancel" color="#aaaaaa" size="26"></icon>
					</view>
					<view class="meal-goods">
						<block v-for="(item, index) in mealDetail.goodsList" :key="index">
							<view class="m-list">
								<view class="list-left" @tap="toDetail" :data-id="item.goods_id">
									<image :src="item.goods_image" mode="widthFix"></image>
								</view>
								<view class="list-right">
									<view class="name" @tap="toDetail" :data-id="item.goods_id">
										{{item.goods_name?item.goods_name:'商品名称'}}
									</view>
									<view class="bottom">
										<view class="right-list">
											<view class="goods_sku" v-if="item.attribute_state==2" @tap.stop="chooseMealSku" :data-index="index">
												<text>{{item.sku_name?item.sku_name:'选规格'}}</text>
												<image src="/static/images/arrow-right.png"></image>
											</view>
										</view>
										<view class="right-list">
											<view class="price-color">￥{{item.online_price?item.online_price:'商品价格'}}</view>
										</view>
									</view>
								</view>
							</view>
						</block>
					</view>
					<view class="meal-buy" @tap="toBuyMeal">{{mealAllMoney}} 购买</view>
				</view>
			</view>
			<view class="kong" v-if="!goodsList && !groupList">暂无商品</view>
		</view>
		<!-- 规格 -->
		<block v-if="showSelectSku">
			<choose-sku :sku="sku" :goodsinfo="skuGoodsInfo" :skuselect="skuSelect" :skutype="3" @close="closeSku"></choose-sku>
		</block>
	</qh-page-view>
</template>

<script>
	var app = getApp().globalData;
	export default {
		data() {
			return {
				goodsList: [],
				groupList: [],
				mealDetail: [],
				showMealDetail: false,
				showSelectSku: false,
				skuPrice: 0,
				skuNum: 0,
				selectSkuDetailId: -1,
				shopItemInfo: {},
				selectArr: [],
				selectGoodsSkuIndex: 0,
				bgOpacity: 0,
				//已选菜单被禁透明度
				z_index: -1,
				//已点菜单的显示等级
				animationData: {},
				//购物车动画
				mealAllMoney: 0.00,
				sku_type: 0,
				//1指定商品的规格  2套餐商品的规格
				skuGoodsInfo: {},
				//规格商品信息
				shoppingIds: [],
				sku: {
					skuImg: '',//规格弹框图片
					skuName: '',//规格名称
					skuSelectIndex: [],//已选规格下标列表
					isSku: true,//是否是规格商品，针对扫码购
					shoppingNum: 1,//选择规格或扫码购商品详情时的加入购物车的数量
					canChangeCarNum: 1,//是否可以修改规格弹框数量
					user_type: 1,//用户类型  1普通  2plus  3常规会员
					skuPrice: '',//商品规格价
					skuNum: '',//商品规格库存
					skuShopMemStatus: 2,//规格商品是否开启普通会员价  1开启  2关闭
					skuShopMemPrice: '',//规格商品普通会员价
					skuPlusMemStatus: 2,//规格商品是否开启PLUS会员价  1开启  2关闭
					skuPlusPrice: '',//规格商品PLUS会员价
					sku_promotion_status: 0,//规格商品是否开启促销
					promotion_price: 0,//规格商品促销价
					canChangeAddNum: true,//是否可以增加
					goods_num: 0,
					showChangeNum: false,//是否显示选择数量
					btnText: '确定', //按钮文字
				},
				selectSkuName: "",
				skuDetailList: "",
				showSelected: "",
				canClicCar: false,
				skuSelect: [],
				goods: {},
				temSkuPrice: ''
			};
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// #ifdef MP-ALIPAY
			if (JSON.stringify(options) == '{}') {
				options = my.getLaunchOptionsSync().query;
			}
			// #endif
			if (options && (options.store_id)) {
				this.$store.store_id = options.store_id;
			}
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: async function() {
			await this.$onLaunched;
			var that = this;
			getApp().globalData.sendRequest({
				url: '/Goods/plusGoods_v1',
				type: "post",
				success: function(res) {
					if (res.status == 1) {
						that.setData({
							goodsList: res.goodsList && res.goodsList.length ? res.goodsList : null,
							groupList: res.groupList && res.groupList.length ? res.groupList : null
						});
					}
				}
			});
		},

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage() {
			return {
				title: 'PLUS商品',
				path: '/pages/product/plusGoods/plusGoods?store_id=' + this.$store.store_id +
					'&share_uid=' + app.XcxData.userInfo.uid,
				success: function(res) { // 转发成功
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		methods: {
			closeSku(data) {
				if (data) {
					this.setData({
						selectSkuDetailId: data.selectSkuDetailId,
						selectArr: data.selectArr,
						selectSkuName: data.selectSkuName,
						temSkuPrice: data.temSkuPrice
					})
					this.sureSku();
				} else {
					this.setData({
						showSelectSku: false
					})
				}
			},
			cratedSku: function() {
				var that = this;
				var skuDetailList = this.skuDetailList;
				var shopItemInfo = {};

				for (var i in skuDetailList) {
					shopItemInfo[skuDetailList[i].sku_id_list] = skuDetailList[i];
				}

				this.setData({
					shopItemInfo: shopItemInfo
				});
				this.checkItem();
			},
			checkSku: function(e) {
				var pIndex = e.currentTarget.dataset.pIndex;
				var cIndex = e.currentTarget.dataset.cIndex;
				var that = this;
				var sku = this.sku;
				var skuList = sku.skuList;
				var selectArr = this.selectArr;

				if (selectArr[pIndex] != skuList[pIndex].list[cIndex].id) {
					selectArr[pIndex] = skuList[pIndex].list[cIndex].id;
					sku.skuSelectIndex[pIndex] = cIndex;
				} else {
					selectArr[pIndex] = 0;
					sku.skuSelectIndex[pIndex] = -1;
				}

				this.setData({
					selectArr: selectArr,
					sku: sku
				});
				this.checkItem();
			},
			checkItem: function() {
				var that = this;
				var sku = this.sku;
				var option = sku.skuList;
				var selectArr = this.selectArr;
				var result = []; //定义数组存储被选中的值

				var skuGoodsInfo = that.skuGoodsInfo;

				for (var i in option) {
					result[i] = selectArr[i] ? selectArr[i] : 0;
				}

				for (var i in option) {
					var last = result[i];

					for (var k in option[i].list) {
						result[i] = option[i].list[k].id;
						option[i].list[k].status = this.isMay(result); //在数据里面添加字段isShow来判断是否可以选择
					}

					result[i] = last;
				}

				sku.skuList = option;
				var selectArr = this.selectArr;

				if (selectArr.indexOf(0) == -1) {
					var id_list = selectArr.join(',');
					var goods_sku = this.shopItemInfo[id_list];
					var num = parseInt(goods_sku.goods_num);
					sku.skuPrice = goods_sku.online_price;
					sku.skuNum = parseInt(goods_sku.goods_num);
					sku.skuImg = goods_sku.goods_img;
					this.setData({
						selectSkuDetailId: goods_sku.id,
						sku: sku,
						selectSkuName: goods_sku.name
					});
				} else {
					sku.skuPrice = this.skuGoodsInfo.online_price;
					sku.skuNum = parseInt(this.skuGoodsInfo.goods_num);
					sku.skuImg = this.skuGoodsInfo.goods_image;
					this.setData({
						selectSkuDetailId: -1,
						sku: sku,
						selectSkuName: this.skuGoodsInfo.goods_name
					});
				}
			},
			isMay: function(result) {
				for (var i in result) {
					if (result[i] == 0) {
						return 1;
					}
				}

				var sku = this.shopItemInfo[result];

				if (sku && sku.goods_num * 1000 / 1000 >= 1) {
					return 1;
				} else {
					return 0;
				}
			},
			seeSkuBig: function() {
				var that = this;
				uni.previewImage({
					current: that.sku.skuImg,
					urls: [that.sku.skuImg] // 需要预览的图片http链接列表

				});
			},
			//显示指定商品规格
			chooseSku: function(e) {
				var index = parseInt(e.currentTarget.dataset.index);
				this.goods.selectGoodsSkuIndex = index
				this.setData({
					sku_type: 1,
					skuGoodsInfo: JSON.parse(JSON.stringify(this.goodsList[index])),
					goods: JSON.parse(JSON.stringify(this.goodsList[index])),
					selectGoodsSkuIndex: index,
					showSelectSku: true,
				});

				// this.showGoodsSku(index);
			},
			//显示套餐商品规格
			chooseMealSku: function(e) {
				var index = parseInt(e.currentTarget.dataset.index);
				this.goods.selectGoodsSkuIndex = index
				this.setData({
					sku_type: 2,
					skuGoodsInfo: JSON.parse(JSON.stringify(this.mealDetail.goodsList[index])),
					goods: JSON.parse(JSON.stringify(this.mealDetail.goodsList[index])),
					selectGoodsSkuIndex: index,
					showSelectSku: true,
				});
				// this.showGoodsSku(index);
			},
			showGoodsSku: function(index) {
				var skuGoodsInfo = this.skuGoodsInfo;
				var skuSelectIndex = [];
				var selectArr = [];

				if (skuGoodsInfo.select_sku_id && skuGoodsInfo.select_sku_id != '' && skuGoodsInfo.select_sku_id !=
					0) {
					var tempArr = skuGoodsInfo.sku_id_list;
					tempArr = tempArr.split(',');

					for (var i = 0; i < tempArr.length; i++) {
						var arr = skuGoodsInfo.skuAttr[i].list;

						for (var j = 0; j < arr.length; j++) {
							if (arr[j].id == tempArr[i]) {
								skuSelectIndex.push(j);
								selectArr.push(arr[j].id);
							}
						}
					}
				} else {
					for (var i = 0; i < skuGoodsInfo.skuAttr.length; i++) {
						skuSelectIndex.push(-1);
						selectArr.push(0);
					}
				}

				var sku = this.sku;
				sku.skuSelectIndex = skuSelectIndex;
				sku.skuList = JSON.parse(JSON.stringify(skuGoodsInfo.skuAttr));
				sku.skuImg = skuGoodsInfo.goods_image;
				sku.skuName = skuGoodsInfo.goods_name;
				sku.skuPrice = skuGoodsInfo.online_price;
				sku.skuDetailList = skuGoodsInfo.skuList
				this.setData({
					selectSkuDetailId: 0,
					skuDetailList: skuGoodsInfo.skuList,
					selectArr: selectArr,
					showSelectSku: true,
					selectSkuName: '',
					sku: sku
				});
				this.cratedSku();
			},
			//取消修改规格
			cancelSku: function() {
				// console.log(1)
				this.setData({
					showSelectSku: false
				});
			},
			//确认选择规格
			sureSku: function() {
				var selectSkuDetailId = this.selectSkuDetailId;
				if (selectSkuDetailId > 0) {
					var skuGoodsInfo = this.skuGoodsInfo;

					if (this.sku_type == 1) {
						//指定商品
						var goodsList = this.goodsList;
						var selectGoodsSkuIndex = this.selectGoodsSkuIndex;
						goodsList[selectGoodsSkuIndex].select_sku_id = selectSkuDetailId;
						goodsList[selectGoodsSkuIndex].sku_name = this.selectSkuName;
						goodsList[selectGoodsSkuIndex].sku_id_list = this.selectArr.join(',');
						goodsList[selectGoodsSkuIndex].online_price = this.temSkuPrice;
						this.setData({
							goodsList: goodsList,
							showSelectSku: false
						});
					} else {
						//套餐
						var mealDetail = this.mealDetail;
						var selectGoodsSkuIndex = this.selectGoodsSkuIndex;
						mealDetail.goodsList[selectGoodsSkuIndex].select_sku_id = selectSkuDetailId;
						mealDetail.goodsList[selectGoodsSkuIndex].sku_name = this.selectSkuName;
						mealDetail.goodsList[selectGoodsSkuIndex].online_price = this.temSkuPrice;
						mealDetail.goodsList[selectGoodsSkuIndex].sku_id_list = this.selectArr.join(',');
						this.setData({
							mealDetail: mealDetail,
							showSelectSku: false
						});
						this.reMoney();
					}
				} else {
					uni.showToast({
						title: '请完善规格',
						icon: 'none',
						duration: 1000
					});
				}
			},
			//购买商品
			toBuyGoods: function(e) {
				var index = e.currentTarget.dataset.index;
				var goodsList = this.goodsList;
				var that = this;
				console.log(goodsList[index], 'goodsIndex')
				if (goodsList[index].attribute_state == 2 && !goodsList[index].select_sku_id) {
					this.setData({
						skuGoodsInfo: JSON.parse(JSON.stringify(goodsList[index])),
						sku_type: 1
					});
					this.showGoodsSku(index);
					return;
				}

				getApp().globalData.sendRequest({
					url: '/Shopping/addShopping_v1',
					type: "post",
					showLoading: false,
					data: {
						goods_id: goodsList[index].goods_id,
						num: 1,
						type: 2,
						sku_id: goodsList[index].select_sku_id ? goodsList[index].select_sku_id : ''
					},
					success: function(res) {
						if (res.status == 1) {
							uni.hideLoading();
							uni.navigateTo({
								url: '../../order/Settlement/Settlement?shopping_ids=' + JSON
									.stringify([res.id]) + '&buy_plus_type=1&plus_act_id=' +
									goodsList[index].id + '&plus_time=' + goodsList[index].time
							});
						} else {
							uni.hideLoading();
							uni.showToast({
								title: res.msg ? res.msg : '请求发生错误，请稍后重试',
								icon: 'none',
								duration: 1500,
								mask: false
							});
						}
					},
					fail: function(res) {
						uni.hideLoading();
						uni.showToast({
							title: res.msg ? res.msg : '请求发生错误，请稍后重试',
							icon: 'none',
							duration: 1500,
							mask: false
						});
					}
				});
			},
			seeMeal: function(e) {
				//购买套餐
				var index = e.currentTarget.dataset.index;
				this.setData({
					showMealDetail: true,
					mealDetail: this.groupList[index]
				});
				this.reMoney();
			},
			reMoney: function() {
				var mealAllMoney = 0;
				var goodsList = this.mealDetail.goodsList;

				for (var i = 0; i < goodsList.length; i++) {
					if (goodsList[i].online_price) {
						mealAllMoney += parseFloat(goodsList[i].online_price);
					}
				}

				mealAllMoney = this.reCalculation(mealAllMoney);
				this.setData({
					mealAllMoney: mealAllMoney
				});
			},

			reCalculation(num) {
				var arr = String(num).split('.');
				var num = Math.round(num * 100) / 100;

				if (arr.length == 2 && arr[1].length == 16) {
					var str = arr[1].substring(2);

					if (str == '49999999999998') {
						var num_2 = parseInt(arr[1].substring(0, 2)) + 1;
						num = parseFloat(arr[0] + '.' + num_2);
					}
				}

				return num;
			},

			/**
			 * 商品详情
			 */
			toDetail: function(e) {
				uni.navigateTo({
					url: '/pages/product/details/details?notBuy=1&id=' + e.currentTarget.dataset.id
				});
			},

			/**
			 * 确认购买套餐
			 */
			toBuyMeal: function() {
				var goodsList = this.mealDetail.goodsList;

				for (var i = 0; i < goodsList.length; i++) {
					if (goodsList[i].goods_num < 1) {
						uni.showToast({
							title: '商品-' + goodsList[i].goods_name + '-库存不足',
							icon: 'none',
							mask: false
						});
						return;
					}

					if (goodsList[i].attribute_state == 2) {
						if (!goodsList[i].select_sku_id) {
							this.setData({
								sku_type: 2,
								skuGoodsInfo: JSON.parse(JSON.stringify(goodsList[i]))
							});
							this.showGoodsSku(i);
							return;
						}
					}
				}

				uni.showLoading({
					title: '请求中...'
				});
				this.setData({
					shoppingIds: []
				});
				this.addShopping(0);
			},
			addShopping: function(i) {
				var goodsList = this.mealDetail.goodsList;
				var shoppingIds = this.shoppingIds;
				var that = this;
				getApp().globalData.sendRequest({
					url: '/Shopping/addShopping_v1',
					type: "post",
					showLoading: false,
					data: {
						goods_id: goodsList[i].goods_id,
						num: 1,
						type: 2,
						sku_id: goodsList[i].select_sku_id ? goodsList[i].select_sku_id : ''
					},
					success: function(res) {
						if (res.status == 1) {
							shoppingIds.push(res.id);
							that.setData({
								shoppingIds: shoppingIds
							});

							if (goodsList.length > i + 1) {
								that.addShopping(i + 1);
							} else {
								uni.hideLoading();
								uni.navigateTo({
									url: '../../order/Settlement/Settlement?shopping_ids=' + JSON
										.stringify(shoppingIds) + '&buy_plus_type=2&plus_act_id=' +
										that.mealDetail.id + '&plus_time=' + that.mealDetail.time
								});
							}
						} else {
							uni.hideLoading();
							uni.showToast({
								title: res.msg ? res.msg : '请求发生错误，请稍后重试',
								icon: 'none',
								duration: 1500,
								mask: false
							});
						}
					},
					fail: function(res) {
						uni.hideLoading();
						uni.showToast({
							title: res.msg ? res.msg : '请求发生错误，请稍后重试',
							icon: 'none',
							duration: 1500,
							mask: false
						});
					}
				});
			},

			/**
			 * 关闭套餐列表
			 */
			closeMealDetail: function() {
				this.mealDetail = []
				this.showMealDetail = false
			},
			// 隐藏与显示收款方式
			hideMark: function() {
				var time = 500;
				var showSelected = this.showSelected;
				var animationData = uni.createAnimation({
					transformOrigin: "50% 50%",
					duration: time,
					timingFunction: "ease",
					delay: 0
				});
				var z_index;
				var that = this;

				if (showSelected == 'block') {
					//变关闭
					showSelected = 'none';
					animationData.bottom('-79vw').step();
					z_index = -1;
					this.setData({
						showSelected: showSelected,
						bgOpacity: 0,
						animationData: animationData.export()
					});
					setTimeout(function() {
						that.setData({
							z_index: z_index,
							canClicCar: true
						});
					}.bind(this), time * 4 / 5);
				} else {
					//变显示
					showSelected = 'block';
					animationData.bottom('0rpx').step();
					z_index = 4;
					this.setData({
						showSelected: showSelected,
						z_index: z_index,
						bgOpacity: 0.6,
						animationData: animationData.export()
					});
					setTimeout(function() {
						that.setData({
							canClicCar: true
						});
					}.bind(this), time);
				}
			}
		}
	};
</script>
<style>
	@import "./plusGoods.css";
</style>
